import { resolve } from "path"
import { defineConfig, loadEnv } from "vite"
import vue from "@vitejs/plugin-vue"
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import ViteRestart from "vite-plugin-restart"
import { ElementPlusResolver } from "unplugin-vue-components/resolvers"
// https://vitejs.dev/config/

const envBase = resolve(__dirname, "env")
const alias = {
	"@": resolve(process.cwd(), "./src"),
}
export default ({ mode }: { mode: any }) =>
	defineConfig({
		plugins: [
			vue(),
			AutoImport({
				imports: ["vue", "vue-router"],
				dts: "src/auto-imports.d.ts", // 安装好依赖后，重新运行编译即可自动在根目录下生成此声明文件
				resolvers: [ElementPlusResolver()],
			}),
			Components({
				dts: "src/components.d.ts",
				resolvers: [ElementPlusResolver()],
			}),
			ViteRestart({
				// 通过这个插件，在修改vite.config.js文件则不需要重新运行也生效配置
				restart: ["vite.config.js"],
			}),
		],
		server: {
			host: "0.0.0.0",
			port: Number(loadEnv(mode, envBase).VITE_APP_PORT),
			// 请求代理
			proxy: {
				// 个人习惯，这里就用/dev作为前缀了
				"/api": {
					target: loadEnv(mode, envBase).VITE_APP_API_BASEURL,
					changeOrigin: true,
					// 路径重写，去掉/dev
					rewrite: (path) => path.replace(/^\/api/, ""),
				},
			},
		},
		css: {
			// css预处理器
			preprocessorOptions: {
				scss: {
					// 因为uni.scss可以全局使用，这里根据自己的需求调整
					// additionalData: '@import "./src/styles/global.scss";',
				},
			},
		},
		envDir: resolve(__dirname, "env"),
		resolve: {
			alias,
		},
		build: {
			/** 配置h5打包js,css,img分别在不同文件夹start */
			assetsDir: "static/js/",
			rollupOptions: {
				input: {
					index: resolve(__dirname, "index.html"),
					pay: resolve(__dirname, "pay.html"),
					callback: resolve(__dirname, "callback.html"),
					originCallback: resolve(__dirname, "originCallback.html"),
				},
				output: {
					chunkFileNames: "static/js/[name]-[hash].js",
					entryFileNames: "static/js/[name]-[hash].js",
					assetFileNames: "static/[ext]/[name]-[hash].[ext]",
				},
			},
			/** 配置h5打包js,css,img分别在不同文件夹end */
		},
		esbuild: {
			pure: ["console.log"],
			drop: ["debugger"],
		},
	})
